<template>
  <div>
    <el-upload
      ref="upload"
      :action="action"
      :data="dataObj"
      :list-type="listType"
      :file-list="fileList"
      :show-file-list="showFile"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <el-button type="primary" v-show="listType == 'picture'">点击上传</el-button>
      <div slot="tip" class="el-upload__tip" v-show="listType == 'picture'">只能上传jpg/png文件，且不超过3MB<span>(推荐尺寸{{singleUploadTitle}})</span> <a style="color: #409EFF" @click="iconClick">（点击从素材库导入）</a></div>
      <div class="avatarBox" v-show="listType != 'picture'">
        <img v-if="fileList.length >0" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus"></i>
      </div>
    </el-upload>
    <el-dialog :append-to-body="true"  :visible.sync="dialogVisible">
      <img width="100%" :src="fileList.length >0 ? fileList[0].url:''" alt="">
    </el-dialog>
    <icon-dialog ref="iconDialog" @confirm="dialogConfirm" />
  </div>
</template>
<script>
  import {policy} from '@/api/oss'
  import IconDialog from '@/components/IconDialog'
  import utils from '../../utils/utils.js'
  export default {
    name: 'singleUpload',
    props: {
      value: String,
      listType:{
        type:String,
        default:'picture'
      },
      singleUploadTitle:{
        type:String,
        default:'***'
      }
    },
    watch: {
      value: {
        handler(newVal, oldVal) {
          if(this.value != null && this.value !== '' && this.first){
            this.first = false;//用变量控制第一次才改变值
            this.fileList = [{name:this.value.substr(this.value.lastIndexOf("/") + 1),url:newVal}]
          }
        },
        immediate: true
      },
      listType: {
        handler(newVal, oldVal) {
          if(newVal == 'picture'){
            this.showFile = true
          }else {
            this.showFile = false
          }
        },
        immediate: true
      },
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
    },
    components: {
     IconDialog
    },
    data() {
      return {
        showFile:false,
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        },
        action:'',
        dialogVisible: false,
        fileList:[],
        first:true,
        uuid:'',
        tailing:''
      };
    },
    methods: {
      iconClick(){
        this.$refs.iconDialog.show()
      },
      dialogConfirm(data){
        this.fileList = [{name:data.name, url: data.iconUrl}];
        this.emitInput(this.fileList[0].url);
      },
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        console.log('333')
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        let fileSize = (file.size/1024/1024).toFixed(2)
        if(fileSize > 3){
          this.$message.warning(`图片过大，请上传3M以内的图片`)
          return false
        }
        console.log('444')
        let _self = this;
        this.tailing = file.type.substring(file.type.indexOf('/')+1);
        _self.uuid = utils.getUUID()
        console.log(_self.uuid)
        return new Promise((resolve, reject) => {
          policy().then(response => {
            console.log(response)
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.key = response.data.dir+'/'+_self.uuid+"."+ _self.tailing;
            _self.dataObj.host = response.data.host;
            _self.action = response.data.action;
            console.log(_self.dataObj)
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },
      handleChange(file, fileList) {
        // console.log('666')
        // this.fileList = fileList.slice(-1);
      },
      handleUploadSuccess(res, file) {
        console.log('5555')
        this.fileList = [file];
        this.emitInput(this.dataObj.host + '/' + this.dataObj.dir + '/' +this.uuid+ '.'+this.tailing);
      }
    }
  }
</script>
<style scoped>
  .avatarBox{
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .avatar {
    width: 99%;
    height: 99%;
    display: block;
  }
  /deep/.el-upload__tip{
    max-width: 600px;
  }
  /deep/ .el-upload-list{
    width: 100% !important;
  }
</style>
